package com.walkline.screen;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.http.HttpProtocolConstants;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.util.StringProvider;

import com.walkline.smzdm.SMZDMSDK;
import com.walkline.smzdm.inf.Experience;
import com.walkline.smzdm.inf.ExperienceList;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.network.MyConnectionFactory;
import com.walkline.util.network.WorkQueue;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;

public class SMZDMScreen extends MainScreen
{
	private SMZDMSDK _smzdm = SMZDMSDK.getInstance();
	private WorkQueue _queue = new WorkQueue(3);
	private ListStyleButtonSet _smzdmSet = new ListStyleButtonSet();
	private ListStyleButtonField _item;
	private ForegroundManager _foreground = new ForegroundManager(0);

    public SMZDMScreen()
    {
        super (NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

        //setDefaultClose(false);

		add(_foreground);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run() {getExperienceList(String.valueOf(1));}
		});
    }

    private void getExperienceList(final String page)
    {
    	UiApplication.getUiApplication().invokeLater(new Runnable()
    	{
			public void run()
			{
		    	ExperienceList experienceList;
				RefreshContentsScreen popupScreen = new RefreshContentsScreen(_smzdm, page, RefreshActions.EXPERIENCELIST);
				UiApplication.getUiApplication().pushModalScreen(popupScreen);

				experienceList = popupScreen.getExperienceList();

				if (popupScreen != null) {popupScreen = null;}
				if (experienceList != null)
				{
					refreshExperienceList(experienceList);
				}
			}
		});
    }

    private void refreshExperienceList(ExperienceList experienceList)
    {
    	if (_smzdmSet.getManager() == null) {_foreground.add(_smzdmSet);}
		if (_smzdmSet.getFieldCount() > 0) {_smzdmSet.deleteAll();}

		Vector experiencesVector = experienceList.getExperience();
		Experience experience;

		for (int i=0; i<experiencesVector.size(); i++)
		{
			experience = (Experience) experiencesVector.elementAt(i);
			if (experience != null)
			{
				_item = new ListStyleButtonField(experience);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC) {showExperienceDetailScreen();}
					}
				});

				_smzdmSet.add(_item);
			}
		}

		if (_smzdmSet.getFieldCount() > 0)
		{
			UiApplication.getUiApplication().invokeLater(new Runnable()
			{
				public void run() {refreshExperienceListIcons();}
			});
		}
    }

    private void refreshExperienceListIcons()
    {
		ListStyleButtonField item;

		_queue.removeAll();

		for (int i=0; i<_smzdmSet.getFieldCount(); i++)
		{
			Field object = _smzdmSet.getField(i);

			if (object instanceof ListStyleButtonField)
			{
				item = (ListStyleButtonField) object;
				_queue.execute(new DownloadImages(item));
			}
		}
    }

    class DownloadImages implements Runnable
    {
    	ListStyleButtonField _item;
		MyConnectionFactory cf = new MyConnectionFactory();
    	MyConnectionFactory _factory = new MyConnectionFactory();
    	HttpConnection _conn = null;
    	InputStream inputStream = null;

    	public DownloadImages(ListStyleButtonField item) {_item = item;}

		public void run()
		{
			if (_item.getThumbnailUrl().equalsIgnoreCase("")) {return;}

			ConnectionDescriptor connd = _factory.getConnection(_item.getThumbnailUrl());

			if (connd == null) {return;}

			try {
				_conn = (HttpConnection) connd.getConnection();
				_conn.setRequestProperty(HttpProtocolConstants.HEADER_CONNECTION, HttpProtocolConstants.HEADER_KEEP_ALIVE);

				inputStream = _conn.openInputStream();

				if (inputStream.available() > 0)
				{
					byte[] data = IOUtilities.streamToBytes(inputStream);

					if (data.length == _conn.getLength()) {_item.setThumbnail(data);}
				}

				inputStream.close();
				_conn.close();
			} catch (IOException e) {}
		}
	}

    private void showExperienceDetailScreen()
    {
    	ListStyleButtonField item = (ListStyleButtonField) _smzdmSet.getFieldWithFocus();

    	UiApplication.getUiApplication().pushScreen(new ExperienceDetailsScreen(_smzdm, String.valueOf(item.getExperienceId())));
    }

    private void showExitDialog()
    {
		String[] yesno = {"是 (Y\u0332)", "否 (N\u0332)"};
		Dialog showDialog = new Dialog("确认退出知乎日报？", yesno, null, 0, Bitmap.getPredefinedBitmap(Bitmap.QUESTION), USE_ALL_WIDTH);

		showDialog.doModal();
		if (showDialog.getSelectedValue() == 0) {System.exit(0);}
    }

    private void showAboutScreen()
    {
    	UiApplication.getUiApplication().pushScreen(new AboutScreen());
    }

    protected boolean keyChar(char key, int status, int time)
    {
    	switch (key)
    	{
    		/*
    		case Characters.SPACE:
    			switch (currentPage)
    			{
					case 0:
						if (_dailyStoriesSet.getFieldCount() > 0)
						{
							int count = _dailyStoriesSet.getFieldWithFocusIndex();

							if (count < _dailyStoriesSet.getFieldCount()) {_dailyStoriesSet.getField(count + 1).setFocus();}
						}
						break;
					case 1:
						break;
					case 2:
						break;
				}
    			return true;
    		*/
			case Characters.LATIN_CAPITAL_LETTER_R:
			case Characters.LATIN_SMALL_LETTER_R:
				//refreshStories();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_T:
			case Characters.LATIN_SMALL_LETTER_T:
				//if (_smzdmSet.getFieldCount() > 0) {_smzdmSet.getField(0).setFocus();}
				//if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(0).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_B:
			case Characters.LATIN_SMALL_LETTER_B:
				//if (_smzdmSet.getFieldCount() > 0) {_smzdmSet.getField(_smzdmSet.getFieldCount()-1).setFocus();}
				//if (_dailyStoriesSet.getFieldCount() > 0) {_dailyStoriesSet.getField(_dailyStoriesSet.getFieldCount()-1).setFocus();}
				return true;
			case Characters.LATIN_CAPITAL_LETTER_A:
			case Characters.LATIN_SMALL_LETTER_A:
				showAboutScreen();
				return true;
			case Characters.LATIN_CAPITAL_LETTER_Q:
			case Characters.LATIN_SMALL_LETTER_Q:
				showExitDialog();
				return true;
		}

    	return super.keyChar(key, status, time);
    }

    MenuItem menuRefresh = new MenuItem(new StringProvider("刷新(R\u0332)"), 100, 10)
    {
    	public void run() {}//refreshStories();}
    };

    MenuItem menuAbout = new MenuItem(new StringProvider("关于(A\u0332)"), 100, 60)
    {
    	public void run() {showAboutScreen();}
    };

    MenuItem menuQuit = new MenuItem(new StringProvider("退出(Q\u0332)"), 100, 70)
    {
    	public void run() {showExitDialog();}
    };

    protected void makeMenu(Menu menu, int instance)
    {
    	menu.add(menuAbout);
    	menu.addSeparator();
    	menu.add(menuQuit);

    	super.makeMenu(menu, instance);
    };

    protected boolean onSavePrompt() {return true;}

    //public boolean onClose()
    //{
    //	UiApplication.getUiApplication().requestBackground();

    //	return true;
    //}
}